import {uSelectDevReportDataByQueryVo} from '@/api/alarm'
import {CCard} from '@/components/card'
import {IconImg, ParamOfStatus} from '@/components/image'
import {DeviceSelect} from '@/components/select/device'
import {ParamSelect} from '@/components/select/param'
import {CnBoldP, CnBoldSpan, CnMediumSpan, CnNormalP, CnNormalSpan} from '@/components/text'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {getUserId} from '@/libs/auth'
import {time2str} from '@/libs/date'
import dayjs, {Dayjs} from 'dayjs'
import {selectReportTypeApi} from '@/api/selectlogType'
import './index.less'
import {toAlarmConfig} from '@/libs/pageRedirect'

type TableColumn = CColumn<Alarm.TableData>

export default defineComponent({
  name: 'alarmManagement',
  setup() {
    const {store} = useGlobalAPI()

    const state = reactive<{
      tableDatas: Alarm.TableData[]
      tableTotal: number
      currentDevId: number | undefined
      currentParamCode: string | undefined
      dateRange: [string, string]
      pagation: Paging
      tableLoading: boolean
    }>({
      currentDevId: undefined,
      currentParamCode: undefined,
      dateRange: ['', ''],
      tableDatas: [],
      tableTotal: 0,
      pagation: {
        page: 1,
        size: 20
      },
      tableLoading: false
    })

    const columns: TableColumn[] = [
      {
        title: '设备',
        dataIndex: 'devName'
      },
      {
        title: '内容',
        dataIndex: 'devReportContent',
        customRender({record, text}) {
          return <ParamOfStatus status={record.paramStatus}>{text}</ParamOfStatus>
        }
      },
      {
        title: '时间',
        dataIndex: 'devReportTime'
        // customRender({text}) {
        //   let value = time2str(text)
        //   return value
        // }
      }
    ]

    const disposeDataRangeDataFunc = (data: any) => {
      let obj = {
        startTime: '',
        endTime: ''
      }
      if (data[0] == '') {
      } else {
        obj.startTime = data[0].format('YYYY-MM-DD 00:00:00')
      }

      if (data[1] == '') {
      } else {
        obj.endTime = data[1].format('YYYY-MM-DD 23:59:59')
      }
      return obj
    }

    function getTableData() {
      const userId = getUserId()
      if (!userId) return
      state.tableLoading = true
      let timeData = disposeDataRangeDataFunc(state.dateRange)
      const startTime = timeData.startTime
      const endTime = timeData.endTime
      uSelectDevReportDataByQueryVo({
        userId,
        devId: state.currentDevId,
        startTime,
        endTime,
        page: 1,
        size: 20,
        paramCode: state.currentParamCode,
        reportCode: currentSelectedTypeCode.value
      })
        .then(res => {
          state.tableDatas = res.data.list
          state.tableTotal = res.data.total
          nextTick(() => {
            store.dispatch('layoutMain/MAINSCROLLTOTOP')
          })
          state.tableLoading = false
        })
        .catch(err => {
          state.tableLoading = false
        })
    }

    function resetSearchLine() {
      state.currentDevId = undefined
      state.currentParamCode = undefined
      state.dateRange = ['', '']
    }

    watch(
      () => state.currentDevId,
      n => {
        getTableData()
      }
    )

    watch(
      () => state.currentParamCode,
      n => {
        getTableData()
      }
    )

    watch(
      () => state.dateRange,
      n => {
        getTableData()
      },
      {deep: true}
    )

    watch(
      () => state.pagation,
      n => {
        getTableData()
      },
      {deep: true}
    )

    // watch(
    //   () => currentSelectedTypeCode.value,
    //   n => {
    //     getTableData()
    //   },
    //   {deep: true}
    // )

    // 类型列表
    const reportTypeDataList = ref([])

    // 当前选择的类型code
    const currentSelectedTypeCode = ref('')

    // 查询类型列表数据的函数
    const selectReportTypeFunc = async () => {
      const res = await selectReportTypeApi()
      // console.log(res, 'resres')
      reportTypeDataList.value = res.data
      console.log(reportTypeDataList.value)
    }
    onMounted(() => {
      getTableData()
      selectReportTypeFunc()
    })

    const tagCheckChange = (currentCode: any, e: any) => {
      console.log(currentCode)
      currentSelectedTypeCode.value = currentCode
      getTableData()
    }

    // const tagClassFunc = (code: string) => {
    //   let retStr = ''
    //   switch (code) {
    //     case '0173':
    //       if (currentSelectedTypeCode.value == code) {
    //         retStr = 'tag_red'
    //       }

    //       break
    //     case '0174':
    //       if (currentSelectedTypeCode.value == code) {
    //         retStr = 'tag_orange'
    //       }
    //       break
    //     default:
    //       break
    //   }
    //   return retStr
    // }

    return () => (
      <div class=''>
        <CnBoldP class='mt-11 text-20'>报警管理</CnBoldP>
        <CnNormalP class='mt-6 text-4xText'>根据您设置的报警标准，将设备检测情况汇报给您</CnNormalP>
        <CCard class='mt-20 bg-white' title='报警信息' canHoverMove={false}>
          <div class='mt-16 inline-grid grid-cols-4 gap-x-16 mb-19 type_box'>
            {/* <CnBoldSpan>报警类型：</CnBoldSpan>
            <CnNormalSpan>设备在线</CnNormalSpan>
            <CnNormalSpan>设备离线</CnNormalSpan>
            <CnNormalSpan>水质</CnNormalSpan> */}
            <CnBoldSpan>报警类型：</CnBoldSpan>
            <div class='tag_checked_box'>
              <a-checkable-tag
                checked={currentSelectedTypeCode.value == ''}
                onChange={(e: any) => {
                  tagCheckChange('', e)
                }}
              >
                <CnNormalSpan>所有类型</CnNormalSpan>
              </a-checkable-tag>
              {reportTypeDataList.value.map((rtdl, i) => (
                <a-checkable-tag
                  class={`${
                    currentSelectedTypeCode.value == rtdl.reportCode
                      ? 'tags tag_' + rtdl.reportCode
                      : ''
                  }`}
                  checked={currentSelectedTypeCode.value == rtdl.reportCode}
                  onChange={(e: any) => {
                    tagCheckChange(rtdl.reportCode, e)
                  }}
                >
                  <CnNormalSpan>{rtdl.reportName}</CnNormalSpan>
                </a-checkable-tag>
              ))}
            </div>
          </div>
          <div class='flex items-center mb-19'>
            <CnBoldSpan class='inline-flex  items-center mr-16'>选择设备：</CnBoldSpan>
            <DeviceSelect
              class='inline-block'
              v-model={[state.currentDevId, 'value']}
            ></DeviceSelect>
          </div>

          {state.currentDevId ? (
            <div class='flex items-center mb-19'>
              <CnBoldSpan class='inline-flex items-center mr-16'>选择参数：</CnBoldSpan>
              <ParamSelect
                v-model={[state.currentParamCode, 'value']}
                devId={state.currentDevId}
                lazy={false}
              ></ParamSelect>
            </div>
          ) : null}

          <div class='flex items-center'>
            <CnBoldSpan class='mr-16'>时间范围：</CnBoldSpan>

            <a-range-picker
              class='mr-16'
              v-model={[state.dateRange, 'value']}
              allowClear={false}
            ></a-range-picker>

            <div class='inline-grid grid-cols-3 gap-x-16'>
              <a-button class='bg-primary'>
                <div class='flex items-center'>
                  <IconImg class='w-16 h-16 mr-8' imgName='magnifying-glass'></IconImg>
                  <CnNormalSpan class='text-white' onClick={getTableData}>
                    查询
                  </CnNormalSpan>
                </div>
              </a-button>
              <a-button class='bg-info'>
                <CnNormalSpan class='text-white' onClick={() => resetSearchLine()}>
                  重置
                </CnNormalSpan>
              </a-button>
              <a-button class='bg-redirectBtn'>
                <CnNormalSpan onClick={toAlarmConfig}>报警配置</CnNormalSpan>
              </a-button>
            </div>
          </div>
          {/* <SplitLine class='mx-16'></SplitLine> */}

          <a-table
            class='mt-20'
            id='alarmTable'
            loading={state.tableLoading}
            columns={columns}
            dataSource={state.tableDatas}
            pagination={{
              current: state.pagation.page,
              pageSize: state.pagation.size,
              size: 'small',
              total: state.tableTotal,
              showTotal: (total: number) => `共 ${total} 条`,
              onChange: (page: number, size: number) => {
                console.log(page, size)
                state.pagation = {
                  page,
                  size
                }
              }
            }}
          ></a-table>
        </CCard>
      </div>
    )
  }
})
